package com.pdsu.alumni.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.pdsu.alumni.common.result.Result;
import com.pdsu.alumni.pojo.CommonUser;
import com.pdsu.alumni.pojo.Honor;
import com.pdsu.alumni.pojo.User;
import com.pdsu.alumni.pojo.UserRole;
import com.pdsu.alumni.service.ICommonUserService;
import com.pdsu.alumni.service.IHonorService;
import com.pdsu.alumni.service.UserRoleService;
import com.pdsu.alumni.service.UserService;
import com.pdsu.alumni.util.DateUtil;
import com.pdsu.alumni.util.ExcelUtils;
import com.pdsu.alumni.util.MD5;
import com.pdsu.alumni.util.ShortUUID;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Acerola
 * @since 2022-01-07
 */

@Api(tags = "校友控制层")
@Slf4j
@RestController
@RequestMapping("/commonuser")
public class CommonUserController {

    @Autowired
    private ICommonUserService commonUserService;
    @Autowired
    private ExcelUtils excelUtils;
    @Autowired
    private UserService userService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private IHonorService honorService;
    @Autowired
    private MD5 md5;


    @ApiOperation(value = "获取所有校友")
    @GetMapping("/list")
    @RequiresAuthentication
    //@RequiresPermissions("")
    @ResponseBody
    @CrossOrigin
    public Result getAllUser() {
        QueryWrapper<CommonUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("state", 0);
        queryWrapper.eq("deleted", 1);
        List<CommonUser> list = commonUserService.list(queryWrapper);
        return new Result().success().put(list);
    }

    @ApiOperation(value = "根据院系获取校友")
    @GetMapping("/listByFaculty")
    @RequiresAuthentication
    //@RequiresPermissions("")
    @ResponseBody
    @CrossOrigin
    public Result getUserByFaculty(Integer id) {
        QueryWrapper<CommonUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("state", 0);
        queryWrapper.eq("deleted", 1);
        List<CommonUser> list = commonUserService.list(queryWrapper);
        return new Result().success().put(list);
    }

    @ApiOperation(value = "通过id获取校友")
    @PostMapping("/getOne")
    @RequiresAuthentication
    //@RequiresPermissions("")
    @ResponseBody
    @CrossOrigin
    public Result getUserById(@RequestBody Map map) {
        Object object = map.get("id");
        Integer id = JSON.parseObject(JSON.toJSONString(object), Integer.class);
        QueryWrapper<CommonUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("cuser_id", id);
        queryWrapper.eq("state", 0);
        queryWrapper.eq("deleted", 1);
        CommonUser commonUser = commonUserService.getOne(queryWrapper);
        if (commonUser == null) {
            return new Result().success("你查询的用户不存在");
        }
        return new Result().success().put(commonUser);
    }

    @ApiOperation(value = "更新校友信息")
    @PostMapping("/update")
    @RequiresAuthentication
    //@RequiresPermissions("")
    @ResponseBody
    @CrossOrigin
    public Result<?> userUpdate(@RequestBody Map map) {
        Object res = map.get("user");
        Object oldIdcard = map.get("oldIdCard");
        CommonUser commonUser = JSON.parseObject(JSON.toJSONString(res), CommonUser.class);
        commonUserService.updateById(commonUser);
        QueryWrapper<Honor> honorQueryWrapper = new QueryWrapper<>();
        honorQueryWrapper.eq("h_uid", oldIdcard);
        Honor one = honorService.getOne(honorQueryWrapper);
        if (one == null) {
            return new Result<>().success();
        }
        one.setHUid(commonUser.getCuserCard());
        honorService.updateById(one);
        return new Result<>().success();
    }

    @ApiOperation(value = "删除校友")
    @PostMapping("/delete")
    @RequiresAuthentication
    //@RequiresPermissions("")
    @ResponseBody
    @CrossOrigin
    public Result<?> userDelete(@RequestBody Map map) {
        Object res = map.get("user");
        CommonUser commonUser = JSON.parseObject(JSON.toJSONString(res), CommonUser.class);
        commonUser.setState(3);
        commonUser.setDeleted(0);
        commonUserService.updateById(commonUser);
        //删除校友表同时,软删除user表
        UpdateWrapper<User> userUpdateWrapper = new UpdateWrapper<>();
        userUpdateWrapper.eq("user_account", commonUser.getCuserAccount()).set("user_del_flag", 0);
        // TODO 同时删除用户角色关联表
        userRoleService.removeById(userRoleService.getOne(new QueryWrapper<UserRole>().eq("user_id", new QueryWrapper<User>().eq("user_account", commonUser.getCuserAccount()))).getId());
        return new Result<>().success();
    }

    @ApiOperation(value = "手动添加校友")
    @PostMapping("/addByHand")
    @RequiresAuthentication
    //@RequiresPermissions("")
    @ResponseBody
    @CrossOrigin
    public Result<?> userInsterByHand(@RequestBody Map map) {
        Object res = map.get("user");
        CommonUser commonUser = JSON.parseObject(JSON.toJSONString(res), CommonUser.class);
        commonUser.setState(0);
        commonUser.setDeleted(1);
        commonUser.setCuserNiceuser(0);
        //手动添加,需要把用户手机号
        if (commonUser.getCuserAccount() == null) {
            commonUser.setCuserAccount(commonUser.getCuserPhone());
        }
        commonUserService.save(commonUser);
        //用户表也需要同步添加校友
        User user = new User();
        user.setUserAccount(commonUser.getCuserAccount());
        user.setUserPassword(md5.encrypt(commonUser.getCuserPassword()));
        user.setUserDelFlag(0);
        user.setUserState(1);
        user.setUserCreatetime(DateUtil.formatTime(new Date()));
        user.setUserUpdateTime(DateUtil.formatTime(new Date()));
        userService.save(user);
        //添加角色表, 设置角色为普通校友
        QueryWrapper<User> commonUserQueryWrapper = new QueryWrapper<>();
        commonUserQueryWrapper.eq("user_account", commonUser.getCuserAccount());
        User user1 = userService.getOne(commonUserQueryWrapper);
        UserRole userRole = new UserRole();
        userRole.setUserId(user1.getUserId());
        userRole.setRoleId("1501887565257535490");
        userRoleService.save(userRole);
        return new Result<>().success();
    }

    @ApiOperation(value = "获取待审核注册用户")
    @GetMapping("/listReg")
    @RequiresAuthentication
    //@RequiresPermissions("")
    @ResponseBody
    @CrossOrigin
    public Result<?> userInsterByHand() {
        QueryWrapper<CommonUser> commonUserQueryWrapper = new QueryWrapper<>();
        commonUserQueryWrapper.eq("state", 2);
        commonUserQueryWrapper.eq("deleted", 1);
        List<CommonUser> commonUserList = commonUserService.list(commonUserQueryWrapper);
        return new Result<>().success().put(commonUserList);
    }

    @ApiOperation(value = "审核通过")
    @PostMapping("/regSuccess")
    @RequiresAuthentication
    //@RequiresPermissions("")
    @ResponseBody
    @CrossOrigin
    public Result<?> regSuccess(@RequestBody Map map) {
        Object res = map.get("user");
        CommonUser commonUser = JSON.parseObject(JSON.toJSONString(res), CommonUser.class);
        commonUser.setState(0);
        commonUser.setDeleted(1);
        commonUser.setCuserNiceuser(0);
        commonUserService.updateById(commonUser);

        User user1 = userService.getOne(new QueryWrapper<User>().eq("user_account", commonUser.getCuserAccount()));
        user1.setUserDelFlag(1);
        userService.updateById(user1);

        //添加角色表, 设置角色为普通校友
        QueryWrapper<User> commonUserQueryWrapper = new QueryWrapper<>();
        commonUserQueryWrapper.eq("user_account", commonUser.getCuserAccount());
        User user2 = userService.getOne(commonUserQueryWrapper);
        UserRole userRole = new UserRole();
        userRole.setUserId(user2.getUserId());
        userRole.setRoleId("1501887565257535490");
        userRoleService.save(userRole);
        return new Result<>().success("审核通过");
    }

    @ApiOperation(value = "审核不通过")
    @PostMapping("/regFail")
    @RequiresAuthentication
    //@RequiresPermissions("")
    @ResponseBody
    @CrossOrigin
    public Result<?> regFail(@RequestBody Map map) {
        Object res = map.get("user");
        CommonUser commonUser = JSON.parseObject(JSON.toJSONString(res), CommonUser.class);
        commonUser.setState(3);
        commonUser.setDeleted(0);
        commonUserService.updateById(commonUser);
        return new Result<>().success("审核不通过");
    }


    @ApiOperation(value = "导入excel添加校友")
    @PostMapping("/addByExcel")
    @RequiresAuthentication
    //@RequiresPermissions("")
    @ResponseBody
    @CrossOrigin
    public Result<?> userInsterByExcel(@RequestPart("file") MultipartFile file, HttpServletResponse resp) throws Exception {
        List<CommonUser> result = excelUtils.importExcel(file, 1, 1, CommonUser.class);
        System.out.println(result);
        //导入成功的数据
        for (CommonUser commonUser : result) {
            if (commonUser.getCuserPhone() != null)
                commonUser.setCuserAccount(commonUser.getCuserPhone());
            else
                commonUser.setCuserAccount(ShortUUID.generateShortUuid());
            commonUser.setCuserPassword(md5.encrypt("123456"));
            commonUser.setState(0);
            commonUser.setDeleted(1);
            commonUser.setCuserNiceuser(0);
            commonUserService.save(commonUser);
            //导入校友也需要同步添加到user表,而且直接设置用户为可用
            User user = new User();
            user.setUserAccount(commonUser.getCuserAccount());
            user.setUserPassword(md5.encrypt(commonUser.getCuserPassword()));
            user.setUserDelFlag(1);
            user.setUserState(1);
            user.setUserCreatetime(DateUtil.formatTime(new Date()));
            user.setUserUpdateTime(DateUtil.formatTime(new Date()));
            userService.save(user);
            //添加用户角色关联表,角色设定为普通校友
            QueryWrapper<User> commonUserQueryWrapper = new QueryWrapper<>();
            commonUserQueryWrapper.eq("user_account", commonUser.getCuserAccount());
            User user1 = userService.getOne(commonUserQueryWrapper);
            UserRole userRole = new UserRole();
            userRole.setUserId(user1.getUserId());
            userRole.setRoleId("1501887565257535490");
            userRoleService.save(userRole);
        }
        return new Result<>().success().put(result);
    }
}
